package net.nagaseyasuhito.nicola.page;

import java.util.ArrayList;
import java.util.List;

import net.nagaseyasuhito.nicola.NicolaSession;
import net.nagaseyasuhito.nicola.component.CurrentEntryPanel;
import net.nagaseyasuhito.nicola.component.EntriesTab;
import net.nagaseyasuhito.nicola.component.EntriesWithFriendsTab;
import net.nagaseyasuhito.nicola.component.FansPanel;
import net.nagaseyasuhito.nicola.component.FriendsPanel;
import net.nagaseyasuhito.nicola.component.ReplyEntriesTab;
import net.nagaseyasuhito.nicola.entity.Entry;
import net.nagaseyasuhito.nicola.entity.User;
import net.nagaseyasuhito.nicola.service.EntryService;

import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.apache.wicket.extensions.ajax.markup.html.tabs.AjaxTabbedPanel;
import org.apache.wicket.extensions.markup.html.tabs.AbstractTab;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.model.CompoundPropertyModel;

import com.google.inject.Inject;

@AuthorizeInstantiation("user")
public class MyPage extends BasePage {
	private static final long serialVersionUID = 1L;

	public MyPage() {
		User user = NicolaSession.get().getUser();

		CurrentEntryPanel currentEntryPanel = new CurrentEntryPanel("entry", user);
		this.add(currentEntryPanel.setOutputMarkupId(true));
		this.add(new FriendsPanel("friends", user));
		this.add(new FansPanel("fans", user));
		
		List<AbstractTab> tabs = new ArrayList<AbstractTab>();
		tabs.add(new EntriesWithFriendsTab(user, 10));
		tabs.add(new EntriesTab(user, 10));
		tabs.add(new ReplyEntriesTab(user, 10));
		AjaxTabbedPanel ajaxTabbedPanel = new AjaxTabbedPanel("entries", tabs);
		this.add(ajaxTabbedPanel);

		this.add(new EntryForm("entryForm", user, ajaxTabbedPanel, currentEntryPanel));
	}

	private class EntryForm extends Form {
		private static final long serialVersionUID = 1L;

		public EntryForm(String id, final User user, final Component... updateTargets) {
			super(id, new CompoundPropertyModel(new Entry()));

			this.add(new TextArea("content"));
			this.add(new AjaxButton("submit") {
				private static final long serialVersionUID = 1L;

				@Inject
				private EntryService entryService;

				@Override
				protected void onSubmit(AjaxRequestTarget target, Form form) {
					Entry entry = (Entry) EntryForm.this.getModelObject();
					entry.setUser(user);
					this.entryService.submit(entry);

					EntryForm.this.setModelObject(new Entry());
					target.addComponent(form);
					for (Component component : updateTargets) {
						target.addComponent(component);
					}
				}
			});
		}
	}
}
